<template>
  <span class="haloe-count-up" ref="rootRef"></span>
</template>

<script setup>
defineOptions({
  name: 'CountUp'
})

import CountUp from 'countup.js';
import { ref, watch,onMounted,onUnmounted } from 'vue';
const props=defineProps({
  start: {
    type: Number,
    required: false,
    default: 0
  },
  end: {
    type: Number,
    required: true
  },
  // 小数位数
  decimals: {
    type: Number,
    required: false,
    default: 0
  },
  // 持续时间
  duration: {
    type: Number,
    required: false,
    default: 2
  },
  // countup.js 设置项
  options: {
    type: Object,
    required: false,
    default () {
      return {};
    }
  },
  callback: {
    type: Function,
    required: false,
    default: () => {}
  }
})

let countUpRef=ref();
let rootRef=ref();
watch(()=>props.end,(val)=>{
  if(countUpRef.value&&countUpRef.value.update){
    countUpRef.value.update(val)
  }
})

const init=()=>{
  if (!countUpRef.value) {
    countUpRef.value = new CountUp(
      rootRef.value,
      props.start,
      props.end,
      props.decimals,
      props.duration,
      props.options
    );
    countUpRef.value.start(() => {
      props.callback(countUpRef.value);
    });
  }
}

const start= (callback)=> {
  if (countUpRef.value && countUpRef.value.start) {
    countUpRef.value.start(() => {
      callback && callback(countUpRef.value);
    });
  }
}
const pauseResume= ()=> {
  if (countUpRef.value && countUpRef.value.pauseResume) {
    countUpRef.value.pauseResume();
  }
}
const reset= ()=> {
  if (countUpRef.value && countUpRef.value.reset) {
    countUpRef.value.reset();
  }
}
const update= (newEndVal) =>{
  if (countUpRef.value && countUpRef.value.update) {
    countUpRef.value.update(newEndVal);
  }
}

onMounted(()=>{
  init()
})

defineExpose({
  start,
  pauseResume,
  reset,
  update
})

onUnmounted(() => {
  countUpRef.value=null
})
</script>
